package com.jl.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class CheckServlet extends HttpServlet {

    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        //判断账号存不存在
        String username = req.getParameter("username");
        if(username.length() > 0 && username != null){
            resp.setContentType("application/json;charset=utf-8");
            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/custormer", "root", "root");
                String sql = "select * from custorm where username = ?";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, username);
                boolean execute = preparedStatement.execute();
                if(execute == true) {
                    resp.getWriter().write("验证通过!");
                    resp.setHeader("Refresh", "3;/Login.html");
                }else{
                    resp.getWriter().write("验证失败!");
                    resp.setHeader("Refresh","3;/index.html");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    resultSet.close();
                    preparedStatement.close();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }else{
            resp.getWriter().write("值是空的!");
        }

    }
}
